package org.elastic.compreplatform.crawler.core.thread.task;
import java.io.Serializable;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.elastic.compreplatform.common.util.SpringContextUtil;
import org.elastic.compreplatform.crawler.controller.CraIpProxyController;
import org.elastic.compreplatform.crawler.core.processor.ProxyStat;
import org.elastic.compreplatform.crawler.model.CraIpProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ClassName: VerifyProxyThreadTask 
 * @Description: 代理IP有效性验证，验证失败将从数据库删除（1、连接失败 2、响应时间大于1秒）
 * @author JornTang
 * @date 2018年2月11日
 */
public class VerifyProxyThreadTask implements Runnable,Serializable{  
	private static final long serialVersionUID = -2224584753890457984L;
	private static Logger log = LoggerFactory.getLogger(VerifyProxyThreadTask.class);
    private CraIpProxy proxy;
        
    public VerifyProxyThreadTask(CraIpProxy proxy) {    
        super();
        this.proxy = proxy;
    }    
    public VerifyProxyThreadTask() {    
        super();    
    }
    @Override
    public void run() {
    	CraIpProxyController proxyController = SpringContextUtil.getBean(CraIpProxyController.class);
    	try {
    		HttpClient httpClient = new HttpClient();
            httpClient.getHostConfiguration().setProxy(proxy.getProxyIp(), proxy.getProxyPort());

            // 连接超时时间（默认10秒 10000ms） 单位毫秒（ms）
            int connectionTimeout = 3000;
            // 读取数据超时时间（默认30秒 30000ms） 单位毫秒（ms）
            int soTimeout = 3000;
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);
            //请求新浪微博
            HttpMethod method = new GetMethod("http://mail.sina.com.cn/");

            int statusCode = httpClient.executeMethod(method);
            if(statusCode == 200 && !"verify".equals(proxy.getProxyType())){
				ProxyStat.getProxy().addAndGet(1L);
				proxyController.save(proxy);
            }else if(statusCode!= 200 && "verify".equals(proxy.getProxyType())){
            	proxyController.delete(proxy);
            	ProxyStat.getVerifyProxy().addAndGet(1L);
            }
		} catch (Exception e) {
			if("verify".equals(proxy.getProxyType())){
				proxyController.delete(proxy);
            	ProxyStat.getVerifyProxy().addAndGet(1L);
			}
			log.error("代理IP有效性验证异常");
		} finally{
			proxy = null;
		}
    }
} 
